package cn.yuhe.basic.controller;

import cn.yuhe.basic.annotation.PreAuthorize;
import cn.yuhe.basic.utils.AjaxResult;
import cn.yuhe.basic.utils.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
* @Description: fastdfs接口类
* @Author: Mr.She
* @Version: 1.0
* @Date:  2022/7/1 15:38
*/
@RestController
@RequestMapping("/fastDfs")
public class FastdfsController {

    /**
    * @Title: upload
    * @Description:分布式上传图片
    * @Author: Mr.Qiu
    * @Version: 1.0
    * @Date:  2022/7/2 0:46
    * @Parameters: [file]
    * @Return AjaxResult
    */
    @PostMapping
    public AjaxResult upload(@RequestPart(value = "file", required = true) MultipartFile file){
        try {
            // 1.得到文件的byte数组
            byte[] bytes = file.getBytes();
            // 2.通过工具类得到文件的后缀
            String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
            // 3.调用文件上传工具类，得到fastdfs图片访问地址
            String filePath = FastdfsUtil.upload(bytes, suffix);
            // filePath:/group1/M00/00/5B/CgAIC2K-oa-AfT_WAAEViWqDzpI474.jpg
            return AjaxResult.me().setResultObj(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请重试！");
        }
    }



    /**
    * @Title: delete
    * @Description:分布式删除图片
    * @Author: Mr.Qiu
    * @Version: 1.0
    * @Date:  2022/7/2 0:46
    * @Parameters: [filePath]
    * @Return AjaxResult
    */
    @DeleteMapping // localhost:8080/fastdfs?filePath = /group1/M00/00/5B/CgAIC2K-oa-AfT_WAAEViWqDzpI474.jpg
    public AjaxResult delete(@RequestParam(value = "filePath", required = true) String filePath){
        try {
            // 因为删除需要组名+图片路径，所以我们需要把前端传递进来的图片路径进行分割
            // /group1/M00/00/05/oYYBAGKCO-6AdKyoAAEOykzR2Hc97_350x350.jpeg
            // 1.得到组名和路径名称
            // 1.1.得到组名
            String pathTmp = filePath.substring(1); // group1/M00/00/5B/CgAIC2K-oa-AfT_WAAEViWqDzpI474.jpg
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            // 1.2.得到图片路径
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            // 2.调用工具类方法进行删除，传递组名和图片路径名称
            FastdfsUtil.delete(groupName, remotePath);
            // 3.返回成功信息+文件访问路径
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请重试！");
        }
    }

}
